package com.cd.music.service.impl;

import com.cd.music.dao.AuthCodeRecordDao;
import com.cd.music.dto.ResultBean;
import com.cd.music.dto.UserDto;
import com.cd.music.model.AuthCodeRecord;
import com.cd.music.service.AuthCodeService;
import com.cd.music.utils.FormatValidateUtil;
import com.cd.music.utils.IdUtil;
import com.cd.music.utils.SmsUtil;
import com.cd.music.utils.StringUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


/**
 * @author yxl 余秀良
 * @version 1.0
 * @description: 验证码服务实现
 * @date 2018年03月01日  下午2:25
 * @address: 四川成都
 */
@Service(value = "authCodeService")
public class AuthCodeServiceImpl implements AuthCodeService {
    @Resource
    private AuthCodeRecordDao dao;

    @Override
    public ResultBean senLoginAuthCode(UserDto dto) {
        return dto != null ? execute(dto, SmsUtil.login(dto.getPhone())) : null;
    }

    @Override
    public ResultBean senRegisterAuthCode(UserDto dto) {
        return dto != null ? execute(dto, SmsUtil.register(dto.getPhone())) : null;
    }

    @Override
    public ResultBean senUpdatePwdAuthCode(UserDto dto) {
        return dto != null ? execute(dto, SmsUtil.updatePwd(dto.getPhone())) : null;
    }

    /**
     * @author yxl 余秀良
     * @version 1.0
     * @description: 登录的时候修改验证码
     * @date 2018年03月01日 上午11:41
     * @address: 四川成都
     */
    private void insertAuthCode(String phone, String verificationCode) {
        AuthCodeRecord codeRecord = new AuthCodeRecord();
        codeRecord.setId(IdUtil.getUUID());
        codeRecord.setPhone(phone);
        codeRecord.setIsUse(false);
        codeRecord.setVerificationCode(verificationCode);
        dao.insertAuthCode(codeRecord);
    }

    /**
     * 发送短信
     *
     * @param dto    　UserDto
     * @param method 　方法
     * @param <T>    　泛型
     * @return ResultBean
     */
    private <T> ResultBean execute(UserDto dto, T method) {
        ResultBean.Builder builder = ResultBean.builder();
        if (dto != null) {
            if (!StringUtil.isEmpty(dto.getPhone()) && FormatValidateUtil.isMobile(dto.getPhone())) {
                ResultBean authCodeResultBean = (ResultBean) method;
                if (authCodeResultBean.getIsSuccess()) {
                    //向数据库添加验证码
                    insertAuthCode(dto.getPhone(), authCodeResultBean.getData());
                    //设置返回信息
                    builder.success(true).code(200).message("发送成功");
                } else {
                    builder.success(false).code(500).message(authCodeResultBean.getMessage());
                }
            } else {
                builder.code(500).message("手机号码不正确").success(false);
            }
        } else {
            builder.code(500).message("请检查参数");
        }
        return builder.build();
    }
}
